<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 原料类别 -->
      <el-col :span="4">
        <div class="head-container">
          <el-input
            v-model="materialCategoryName"
            placeholder="请输入原料类别名"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="categoryOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="20">
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="原料编号" prop="materialNo">
            <el-input
              v-model="queryParams.materialNo"
              placeholder="请输入原料编号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="原料名称" prop="materialName">
            <el-input
              v-model="queryParams.materialName"
              placeholder="请输入原料名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="快捷码" prop="shortcutCode">
            <el-input
              v-model="queryParams.shortcutCode"
              placeholder="请输入快捷码"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <!-- <el-form-item label="原料类别" prop="materialCategoryId">
            <el-input
              v-model="queryParams.materialCategoryId"
              placeholder="请输入原料类别"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item> -->
          <el-form-item>
            <el-button
              type="cyan"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['systembasic:material:add']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['systembasic:material:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['systembasic:material:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['systembasic:material:export']"
              >导出</el-button
            >
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="materialList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="原料编号" align="center" prop="materialNo" />
          <el-table-column
            label="原料名称"
            align="center"
            prop="materialName"
          />
          <el-table-column label="快捷码" align="center" prop="shortcutCode" />
          <el-table-column
            label="原料类别"
            align="center"
            prop="materialCategoryName"
          />
          <el-table-column
            label="原料规格"
            align="center"
            prop="materialSpec"
          />
          <el-table-column label="单价" align="center" prop="unitPrice" />
          <el-table-column
            label="原料单位"
            align="center"
            prop="materialUnit"
            :formatter="materialUnitFormat"
          />
          <el-table-column
            label="物料整箱数量"
            align="center"
            prop="qtyPerPkg"
          />
          <el-table-column
            label="管理方式"
            align="center"
            prop="manageType"
            :formatter="manageTypeFormat"
          />
          <el-table-column
            label="是否有效"
            align="center"
            prop="deleteFlag"
            :formatter="deleteFlagFormat"
          />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['systembasic:material:edit']"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['systembasic:material:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改原料管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="原料编号" prop="materialNo">
          <el-input
            v-model="form.materialNo"
            v-bind:disabled="disableEdit"
            placeholder="请输入原料编号"
          />
        </el-form-item>
        <el-form-item label="原料名称" prop="materialName">
          <el-input v-model="form.materialName" placeholder="请输入原料名称" />
        </el-form-item>
        <el-form-item label="快捷码" prop="shortcutCode">
          <el-input v-model="form.shortcutCode" placeholder="请输入快捷码" />
        </el-form-item>
        <el-form-item label="原料类别" prop="materialCategoryId">
          <treeselect
            v-model="form.materialCategoryId"
            :options="categoryOptions"
            :show-count="true"
            placeholder="请选择原料类别"
          />
        </el-form-item>
        <el-form-item label="原料规格" prop="materialSpec">
          <el-input v-model="form.materialSpec" placeholder="请输入原料规格" />
        </el-form-item>
        <el-form-item label="单价" prop="unitPrice">
          <el-input v-model="form.unitPrice" placeholder="请输入单价" />
        </el-form-item>
        <el-form-item label="原料单位" prop="materialUnit">
          <el-select v-model="form.materialUnit" placeholder="请选择原料单位">
            <el-option
              v-for="dict in materialUnitOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物料整箱数量" prop="qtyPerPkg">
          <el-input v-model="form.qtyPerPkg" placeholder="请输入物料整箱数量" />
        </el-form-item>
        <el-form-item label="管理方式" prop="manageType">
          <el-select v-model="form.manageType" placeholder="请选择管理方式">
            <el-option
              v-for="dict in manageTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否有效">
          <el-radio-group v-model="form.deleteFlag">
            <el-radio
              v-for="dict in deleteFlagOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
              >{{ dict.dictLabel }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMaterial,
  getMaterial,
  delMaterial,
  addMaterial,
  updateMaterial,
  exportMaterial,
} from "@/api/systembasic/material";
import { treeselect } from "@/api/systembasic/materialCategory";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Material",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 原料管理表格数据
      materialList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 原料单位字典
      materialUnitOptions: [],
      // 管理方式字典
      manageTypeOptions: [],
      // 是否有效字典
      deleteFlagOptions: [],
      categoryOptions: [],
      materialCategoryName: undefined,
      // 能否编辑编号
      disableEdit: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialNo: null,
        materialName: null,
        shortcutCode: null,
        materialCategoryId: null,
      },
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        materialNo: [
          { required: true, message: "原料编号不能为空", trigger: "blur" },
        ],
      },
    };
  },
  watch: {
    // 根据名称筛选部门树
    materialCategoryName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getList();
    this.getTreeselect();
    this.getDicts("smes_unit").then((response) => {
      this.materialUnitOptions = response.data;
    });
    this.getDicts("manage_type").then((response) => {
      this.manageTypeOptions = response.data;
    });
    this.getDicts("sys_yes_no").then((response) => {
      this.deleteFlagOptions = response.data;
    });
  },
  methods: {
    /** 查询原料管理列表 */
    getList() {
      this.loading = true;
      listMaterial(this.queryParams).then((response) => {
        this.materialList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getTreeselect() {
      treeselect().then((response) => {
        this.categoryOptions = response.data;
        console.log(this.categoryOptions);
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.materialCategoryId = data.id;
      this.getList();
    },
    // 原料单位字典翻译
    materialUnitFormat(row, column) {
      return this.selectDictLabel(this.materialUnitOptions, row.materialUnit);
    },
    // 管理方式字典翻译
    manageTypeFormat(row, column) {
      return this.selectDictLabel(this.manageTypeOptions, row.manageType);
    },
    // 是否有效字典翻译
    deleteFlagFormat(row, column) {
      return this.selectDictLabel(this.deleteFlagOptions, row.deleteFlag);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        rowId: null,
        materialNo: null,
        materialName: null,
        shortcutCode: null,
        materialCategoryId: null,
        unitPrice: 0,
        materialUnit: "GE",
        qtyPerPkg: 0,
        materialCheckNo: null,
        produceCheckNo: null,
        manageType: null,
        deleteFlag: "Y",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.materialNo);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.disableEdit=false;
      this.reset();
      this.open = true;
      this.title = "添加原料管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.disableEdit=true;
      this.reset();
      const materialNo = row.materialNo || this.ids;
      getMaterial(materialNo).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改原料管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.rowId != null) {
            updateMaterial(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMaterial(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const materialNos = row.materialNo || this.ids;
      this.$confirm(
        '是否确认删除原料管理编号为"' + materialNos + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delMaterial(materialNos);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有原料管理数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportMaterial(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
  },
};
</script>
